package 线程池的使用;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;

public class ThreadPollDemo {
	private static final Logger LOGGER=Logger.getLogger("ThreadPoolDemo");
	//使用固定线程数量创建线程池
	public static void FixedThreadPool() {
		ExecutorService pool=Executors.newFixedThreadPool(3);
		for(int i=0;i<3;i++) {
			pool.submit(new Runnable() {
				@Override
				public void run() {
					// TODO 自动生成的方法存根
					LOGGER.info("线程FixedThreadPool创建成功"+Thread.currentThread().getName());
				}
			});
		}
		pool.shutdown();
	}
	//使用ThreadPoolExecutor创建自定义线程池
	public static void ThreadPoolExecutor() {
		/* 
		 * 参数设置 
		 * 1.核心线程数量
		 * 2.最大线程数
		 * 3.空闲临时线程最大存活时间（数值）
		 * 4.空闲临时线程最大存活时间（单位）
		 * 5.任务队列
		 * 6.创建线程的工厂
		 * 7.任务的拒绝策略
		*/
		ThreadPoolExecutor threadPoolExecutor=new ThreadPoolExecutor
				(3, 6, 30, TimeUnit.SECONDS,
				new ArrayBlockingQueue<Runnable>(3),
				Executors.defaultThreadFactory(),
				new ThreadPoolExecutor.AbortPolicy());
		try {
			
		
			for(int i=0;i<10;i++) {
	//			threadPoolExecutor.submit(new Runnable() {
	//				
	//				@Override
	//				public void run() {
	//					// TODO 自动生成的方法存根
	//					LOGGER.info("线程threadPoolExecutor创建成功;"+Thread.currentThread().getName());
	//				}
	//			});
				Future<String> future=threadPoolExecutor.submit(new Callable<String>() {
	
					@Override
					public String call() throws Exception {
						// TODO 自动生成的方法存根
						return Thread.currentThread().getName();
					}
				});
				LOGGER.info(future.get());
			}
		} catch (Exception e) {
			// TODO: handle exception
		}
		finally {
			threadPoolExecutor.shutdown();
		}
	}
	public static void main(String[] args) {
		FixedThreadPool();
	}
}
